<template>
  <Back></Back>
  <div class="header">
    <div style="padding: 10px; display: flex; height: 40px; line-height: 40px">
      <div class="title">文章标题</div>
      <el-input
        placeholder="请输入文章标题(1~100字)"
        class="box"
        maxlength="100"
        show-word-limit
        v-model.trim="content.title"
      ></el-input>
    </div>
  </div>
  <!-- 文章区域 -->
  <MdEditor
    v-model="content.content"
    placeholder="请输入文字内容..."
    :preview="false"
    style="width: 80%; margin-left: 10%; margin-top: 20px"
    @onUploadImg="onUploadImg"
  />
  <PublisherOther
    :dataList="typeList"
    :content="content"
    :tagList="tagList"
    :update="udpateBlog"
    ref="publisherOther"
  ></PublisherOther>

  <!-- 底部 -->
  <div>
    <div class="foot">
      <div class="btn">
        <el-button size="large" round @click="publisherBlog(0)">保存草稿</el-button>
      </div>
      <div class="btn">
        <el-button size="large" round @click="delayPublisher">定时发布</el-button>
      </div>
      <div class="btn fsw-small">
        <el-button
          size="large"
          round
          style="background: #ff8247; color: #fff"
          @click="publisherBlog(1)"
          >发布博客</el-button
        >
      </div>
    </div>
  </div>

  <loading v-if="showLoading"></loading>
  <ChooseTime ref="chooseTime" @select-time="handlerConfirm"></ChooseTime>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import request from '@/util/request'
import { ElNotification } from 'element-plus'
import PublisherOther from '@/components/client/PublisherOther.vue'
import axios from 'axios'
import loading from '@/components/client/loading.vue'
import ChooseTime from '@/components/ChooseTime.vue'
import Back from '@/components/client/Back.vue'

const typeList = ref([])
const tagList = ref([])
const imageList = ref([])
const publisherOther = ref()
const chooseTime = ref()
// 判断当前状态是否是修改，或者新增，0-新增，1-修改
const addOrUpdate = ref(0)
// 修改的文章内容
const udpateBlog = ref({})

const showLoading = ref(false)

const content = ref({
  title: '',
  content: '',
  delayTime: null
})

const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((rev, rej) => {
        const form = new FormData()
        form.append('file', file)
        console.log('file--->', file)
        this.files = files
        // axios
        //   .post('http://localhost:8080/files/upload', form, {
        //     headers: {
        //       'Content-Type': 'multipart/form-data'
        //     }
        //   })
        //   .then((res) => {
        //     console.log(res.data.data.path)
        //     content.value.content += `<br/>![](${res.data.data.path} width="400px" height="auto")`
        //     const obj = {
        //       path: res.data.data.path,
        //       flag: res.data.data.flag
        //     }
        //     imageList.value.push(obj)
        //   })
        //   .catch((error) => rej(error))
      })
    })
  )

  // 方式二
  // callback(
  //   res.map((item: any) => ({
  //     url: item.data.url,
  //     alt: 'alt',
  //     title: 'title'
  //   }))
  // );
}

const delayPublisher = () => {
  chooseTime.value.open()
}

const handlerConfirm = (time) => {
  console.log('选则的时间', time)
  content.value.delayTime = time
  publisherBlog(4)
}

const getType = () => {
  request
    .get('/user/type/list')
    .then((res) => {
      console.log('获取成功：', res)
      typeList.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const getTag = () => {
  request
    .get('/user/tag/list')
    .then((res) => {
      console.log('获取成功：', res)
      tagList.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const pictureUpLoad = async (file)=>{

  return new Promise((resolve,reject)=>{
    console.log('---',file);
    let formData = new FormData()
    formData.append('file', file);  
    // 如果你还想发送额外的字段，比如文件名或其他信息，可以这样添加  
    formData.append('fileName',file.name);  
    axios({
        url: 'http://localhost:8080/files/upload',
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        processData: false,
        data: formData
    }).then(res=>{
      console.log('上传成功',res.data.data.path);
      // picture.value =  res.data.data.path
      resolve(res.data.data.path)
    }).catch(err=>{
      if (err.response) {
          console.error(err.message)
          ElNotification({
            title: 'Error',
            message: err.message,
            type: 'error'
          })
        } else {
          ElNotification({
            title: 'Error',
            message: '网络错误',
            type: 'error'
          })
        }
    })
  })
}

const publisherBlog =async (status) => {
  if (status === 4) {
    if (content.value.delayTime === null) {
      ElNotification.warning('延时时间不能为空')
      return
    }
  }
  showLoading.value = true
  const obj = publisherOther.value.getData()

  const path = await pictureUpLoad(obj.fileObj)

  console.log('上传的图片路径',path);
  const form = {
    id: null,
    title: content.value.title, // 标题-string
    content: content.value.content, // 内容-string
    description: obj.description, // 描述-string
    firstPicture: path, // 首图-string
    model: obj.model, // 类型-integer
    review: obj.review, // 是否开启评论-integer
    tag: obj.tag, // 文章标签-string
    type: obj.type, // 文章分类-integer
    imageList: imageList.value, // 文章插图列表-array:flag-path
    status: status,
    delayTime: content.value.delayTime
  }
  if (addOrUpdate.value === 1) {
    form.id = udpateBlog.value.id
  }
  console.log('其他数据', form)

  request
    .post('/user/blog/insert', form)
    .then((res) => {
      console.log('执行了--->', res)
      setTimeout(() => {
        if (form.status === 0) {
          ElNotification.success('保存成功')
        } else if (form.status === 4) {
          ElNotification.success('提交成功')
        } else {
          ElNotification.success('发布成功，等待审核')
        }
        localStorage.removeItem('update-blog')
        showLoading.value = false
        reset()
      }, 2000)
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }

      setTimeout(() => {
        showLoading.value = false
      }, 500)
    })


  }

const reset = () => {
  content.value = {
    title: '',
    content: '',
    delayTime: null
  }
  imageList.value = []
}

onMounted(() => {
  getType()
  getTag()
  const blog = localStorage.getItem('update-blog')
  if (blog !== null) {
    udpateBlog.value = JSON.parse(blog)
    addOrUpdate.value = 1
    content.value.content = udpateBlog.value.content
    content.value.title = udpateBlog.value.title
  }
  console.log('修改的数据', udpateBlog)
})
</script>

<style scoped>
.foot {
  position: fixed;
  top: 90%;
  left: 0;
  width: 100%;
  height: 70px;
  justify-content: right;
  line-height: 60px;
  z-index: 100;
  background: #fff;
  display: flex;
  border-top: 1px solid #eee;
}

.header {
  width: 80%;
  background: #fff;
  margin-left: 10%;
  margin-top: 60px;
}

.title {
  width: 100px;
  text-align: center;
  color: #6c6c6c;
}

.btn {
  margin-right: 20px;
}
</style>
